package com.example.demo.filter;

import com.example.demo.common.config.ParameterRequestWrapper;
import com.example.demo.constant.Constant;
import com.example.demo.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * parameter filter.
 *
 * @author Mei Ruoxiao
 * @since 2020/9/12
 */
@Slf4j
@Component
@WebFilter(urlPatterns = {"/hello/*"}, filterName = "RequestParameterFilter")
public class RequestParameterFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        if (token == null || "".equals(token) || token.isEmpty()) {
            chain.doFilter(req, response);
            return;
        }
        long userId = JwtUtil.getUserId(token);
        long companyId = JwtUtil.getCompanyId(token);
        if (Objects.isNull(userId) || Objects.isNull(companyId)) {
            chain.doFilter(req, response);
            return;
        }
        final Map<String, Object> parameter = new HashMap<>(16);
        parameter.put(Constant.HeaderKey.COMPANY_ID, companyId);
        parameter.put(Constant.HeaderKey.USER_ID, userId);
        ParameterRequestWrapper wrapper = new ParameterRequestWrapper(req, parameter);
        chain.doFilter(wrapper, response);
    }

    @Override
    public void destroy() {

    }
}
